import sys
import main
import csv
import pathlib
from mainwindow import Ui_MainWindow
from PyQt5.QtWidgets import QApplication,QMainWindow

class my_Combobox(Ui_MainWindow):
    def __init__(self,mainWindow):
        super().__init__()
        self.setupUi(mainWindow)
        self.initUI()
    def initUI(self):
        self.start_pushButton.clicked.connect(self.start_btn)
        self.exit_pushButton.clicked.connect(self.exit_btn)
        self.save_pushButton.clicked.connect(self.save_btn)
        self.text_browser()

    def save_btn(self):
        account = self.account_lineEdit.text()
        pwd = self.password_lineEdit.text()
        main.write_account(account,pwd)
        compus_url = self.compus_url_lineEdit.text()
        main.write_url(compus_url)

    def start_btn(self):
        if main.verify('https://www.baidu.com'):
            self.textBrowser.setText('已连接网络')
        else:
            if main.signin() == 1:
                self.textBrowser.setText('账号或密码错误')
            elif main.signin() == 2:
                self.textBrowser.setText('账户正确，但无法访问网络')
            elif main.signin() == 0:
                self.textBrowser.setText('不在校园网连接范围内')

    def exit_btn(self):
        exit()

    def text_browser(self):
        if main.verify('https://www.baidu.com'):
            self.textBrowser.setText('已连接网络')
        else:
            self.textBrowser.setText('未连接网络')

if __name__ == '__main__':
    path1 = pathlib.Path('account.csv')
    path2 = pathlib.Path('datatime.csv')
    path3 = pathlib.Path('url.csv')
    if path1.exists():
        None
    else:
        with open('account.csv', 'a', newline='') as f:
            writer = csv.writer(f)
            writer.writerow(['username', 'password'])
            f.close()
    if path2.exists():
        None
    else:
        with open('datatime.csv', 'a', newline='') as f:
            writer = csv.writer(f)
            writer.writerow(['account', 'time','status'])
            f.close()
    if path3.exists():
        None
    else:
        with open('url.csv', 'a', newline='') as f:
            writer = csv.writer(f)
            writer.writerow(['url'])
            f.close()
    if main.csv_line('account.csv') > 1 and main.csv_line('url.csv') > 1:
        with open("url.csv", "r", newline="") as f:  # 读取校园网网址
            data = csv.reader(f)
            next(data)
            data = list(data)
            url = data[0][0]
            f.close()
        if main.verify(url):
            if not main.verify('https://www.baidu.com'):
                main.signin()
    app = QApplication(sys.argv)
    mw = QMainWindow()
    ui = my_Combobox(mw)
    mw.show()
    sys.exit(app.exec())
